/* 参考链接
 https://www.cnblogs.com/elnino/p/11171406.html
*/

package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
)

const (
    maxPartSize = int64(5 * 1024 * 1024)
    maxRetries  = 3
    localS3Region = "default"  // 本地分布式存储、对象存储使用default即可
)

type S3Mgmt struct {
    region      string `s3 region`
    host        string `S3 host`
    DoName      string `S3 doname`
    bucket_id   string `bucket_id`
    PathStyle   bool   `S3 url style, true means you can use host directly,  false means bucket_id.doname will be used`
    AccessKey   string `aws s3 aceessKey`
    SecretKey   string `aws s3 secretKey`
    block_size  int64  `block_size`
}

var S3 S3Mgmt

type MyProvider struct{}

func (m *MyProvider) Retrieve() (credentials.Value, error) {
    return credentials.Value{
        AccessKeyID:     S3.AccessKey, //"9YGYCFH1V3QUT4B9KZD1",
        SecretAccessKey: S3.SecretKey, //"9hdiwSjCfyrZPKGObH8Kctdur8PiBPJu3B4zGYaZ",
    }, nil
}

func (m *MyProvider) IsExpired() bool { 
    return false 
}

//func (this *S3Mgmt) ConnInit() error {
//    // "http://s3.devopscloud.com"
//    this.host = beego.AppConfig.String("S3::host")
//    if len(this.host) <= 0 {
//        return errors.New("S3 conf host is nil")
//    }
//    this.bucket_id = beego.AppConfig.String("S3::bucket_id")
//    if len(this.bucket_id) <= 0 {
//        return errors.New("S3 conf bucket_id is nil")
//    }
//    this.block_size, _ = beego.AppConfig.Int64("S3::block_size")
//    if this.block_size <= 5*1024*1024 {
//        this.block_size = 5 * 1024 * 1024
//    }
//    return nil
//}


func (this *S3Mgmt) ConnInit(host string, bucket string, accesskey string, secretkey string) error {
    this.region = localS3Region   // 本地分布式存储、对象存储使用default即可
    this.host = host
    this.bucket_id = bucket
    this.AccessKey = accesskey
    this.SecretKey = secretkey
    this.PathStyle = true
    this.block_size = 8 * 1024 * 1024

    return nil
}

func (this *S3Mgmt) NewSessionConnect() (*s3.S3, error) {
    ///////////////创建连接
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        Config: aws.Config{
            Region: aws.String(this.region), //Required 目前尚未分区，填写default即可
            //EndpointResolver: endpoints.ResolverFunc(s3CustResolverFn),
            Endpoint:         &this.host,
            S3ForcePathStyle: &this.PathStyle,
            Credentials:      credentials.NewCredentials(&MyProvider{}),
        },
    }))
    // Create the S3 service client with the shared session. This will
    // automatically use the S3 custom endpoint configured in the custom
    // endpoint resolver wrapping the default endpoint resolver.
    return s3.New(sess), nil
}
